package com.bitcoin.scheduler.task;

import com.bitcoin.scheduler.service.BccBasicInfoService;
import com.bitcoin.scheduler.service.BccPriceInfoService;
import com.bitcoin.scheduler.service.ServiceException;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Set;

/**
 * 币基本信息爬虫数据清洗任务
 */
@Service
@Slf4j
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class BccPriceInfoTask implements Job {

    @Autowired
    private BccBasicInfoService basicInfoService;
    @Autowired
    private BccPriceInfoService priceInfoService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        int step = 1;
        Date stepDate;
        Set<String> keySet = Sets.newConcurrentHashSet();
        if (context.getMergedJobDataMap().containsKey("priceTime")) {
            stepDate = (Date) context.getMergedJobDataMap().get("priceTime");
        }
        else {
            stepDate = getStepDate(step);
        }
        try {
            keySet = priceInfoService.syncPriceDetail(stepDate, true);
        } catch (ServiceException e) {
            log.warn(e.getMessage());
        }

        //更新有关BCC的缓存
        updateCache(keySet);
    }

    /**
     * 取得步长时间
     *
     * @param step 步长
     * @return 步长时间
     */
    private Date getStepDate(int step) {
        Calendar current = Calendar.getInstance();
        int minute = current.get(Calendar.MINUTE) - current.get(Calendar.MINUTE) % step;
        current.set(Calendar.MINUTE, minute);
        current.set(Calendar.SECOND, 0);
        current.set(Calendar.MILLISECOND, 0);
        return current.getTime();
    }

    //更新缓存
    private void updateCache(Collection<String> keyList) {
        log.info("同步更新价格缓存,缓存KEY:{}", StringUtils.join(keyList, ","));
        for (String bccId : keyList) {
            basicInfoService.getDao().findAllBccId();
        }
    }
}
